<template>
  <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" style="border-bottom: 1px solid #ccc" />
  <Editor :style="{height:props.eheight+'px'}" style="overflow-y: hidden" v-model="props.content" :defaultConfig="editorConfig" :mode="mode"
    @onCreated="handleCreated" @onChange="handleChange" />
  <div id="editor-container"></div>
</template>

<script setup>
import { shallowRef, ref, onMounted, onBeforeUnmount, watch } from "vue";

import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { createEditor } from "@wangeditor/editor";

import requestImg from "@/utils/uploadImg";

const emits = defineEmits(["getContent"]);

import "@wangeditor/editor/dist/css/style.css";
import { message } from "ant-design-vue"; // 引入 css
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref("");

const toolbarConfig = {};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {},
};
editorConfig.MENU_CONF["uploadImage"] = {
  async customUpload(file, insertFn) {
    requestImg(file).then(function (res) {
      if (res.code == 0) {
        message.success("上传成功");
        insertFn(res.data[0]["url"], null, null);
      }
    });
  },
};

const mode = "default";

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const props = defineProps({
  content: {
    type: String,
    default: "",
  },
  eheight:{
    type:Number,
    default:400
  },
  item: {
    type: Object,
    default: () => {
      return {};
    },
  },
});
// 监听内容
watch(
  () => props.content,
  (newVal, oldVal) => {
    if (newVal) {
      valueHtml.value = newVal;
    } else {
      valueHtml.value = ""
    }
  }
);
// 清空编辑器内容
const clear = () => {
  const editor = editorRef.value;
  editor.clear();
};
const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

const handleChange = (editor) => {
  var newHtml = editor.getHtml();
  //传值给父组件
  if (props.item) {
    emits("getContent", newHtml, props.item);
  } else {
    emits("getContent", newHtml);
  }
};
// 暴露方法
defineExpose({
  clear,
});
</script>

<style scoped></style>
